package com.marisfrolg.storage;

import java.lang.ref.WeakReference;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.ksoap2.serialization.SoapObject;

import com.beardedhen.androidbootstrap.BootstrapEditText;
import com.beardedhen.androidbootstrap.FontAwesomeText;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.marisfrolg.entity.ItemWithBin;
import com.marisfrolg.entity.json.User;
import com.marisfrolg.util.WebServicesUtil;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class CheckedActivity extends ItemActivity {
	@ViewInject(R.id.defferenceitems)
	private LinearLayout defferenceitems;
	@ViewInject(R.id.refreshdefference)
	private FontAwesomeText refreshdefference;
	@ViewInject(R.id.searchcode)
	private BootstrapEditText searchcode;
	@ViewInject(R.id.searchcode2)
	private BootstrapEditText searchcode2;
	private WebServicesUtil ws;
	private WSHandler handler;
	private Map<String, List<ItemWithBin>> items = new HashMap<String, List<ItemWithBin>>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_checked);
		ViewUtils.inject(this);
		handler = new WSHandler(this);
		ws = new WebServicesUtil(this,handler);
		HashMap<String, Object> params = new HashMap<String, Object>();
		Gson gson=new Gson();
		Type type = new TypeToken<User>() {}.getType();
		params.put("USER", gson.toJson(loginUser, type));
		ws.call(WebServicesUtil.ACTION_GetDifference, params,
				WebServicesUtil.URL_ACTION_GetDifference,
				WebServicesUtil.METHOD_ACTION_GetDifference);
		progressDialog = ProgressDialog.show(CheckedActivity.this, "查询中", "请稍候...", true, true);
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.setOnCancelListener(new OnCancelListener() {
			public void onCancel(DialogInterface dialog) {
				WebServicesUtil.setConnectionTimeOut();
			}
		});
		searchcode.addTextChangedListener(new TextWatcher(){
			public void afterTextChanged(Editable arg0) {
				refresh(searchcode.getText()+"",searchcode2.getText()+"");
			}
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				
			}});
		searchcode2.addTextChangedListener(new TextWatcher(){
			public void afterTextChanged(Editable arg0) {
				refresh(searchcode.getText()+"",searchcode2.getText()+"");
			}
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				
			}});
		refresh();
	}

	@OnClick(R.id.refreshdefference)
	public void refreshDeff(View v) {
		HashMap<String, Object> params = new HashMap<String, Object>();
		ws.call(WebServicesUtil.ACTION_GetDifference, params,WebServicesUtil.URL_ACTION_GetDifference,WebServicesUtil.METHOD_ACTION_GetDifference);
		progressDialog = ProgressDialog.show(this, "查询中", "请稍候...", true, false);
		refresh();
	}
	
	private void refresh(){
		refresh("","");
	}
	private void refresh(String keyword,String keyword2) {
		defferenceitems.removeAllViews();
		for (String i : items.keySet()) {
			if(!i.contains(keyword.trim().toUpperCase(new Locale("US")))){
				continue;
			}
			List<ItemWithBin> list = items.get(i);
			LayoutInflater inflater = LayoutInflater.from(this);
			View check = inflater.inflate(R.layout.checked_check, null);
			TextView tvcode = (TextView) check.findViewById(R.id.checkcode);
			tvcode.setText(i);
			LinearLayout checklist = (LinearLayout) check
					.findViewById(R.id.checkeditems);
			boolean hasone=false;
			for (ItemWithBin itemWithBin : list) {
				View v = inflater.inflate(R.layout.checked_model, null);// 直接从布局文件转化为view对象
				TextView tv = (TextView) v.findViewById(R.id.modelcode);
				if(!itemWithBin.ProductNumber.contains(keyword2.trim().toUpperCase(new Locale("US")))){
					continue;
				}
				hasone=true;
				tv.setText(itemWithBin.ProductNumber + "");
				TextView tvq = (TextView) v.findViewById(R.id.modelnum);
				tvq.setText(itemWithBin.Quantity + "");
				if (itemWithBin.Quantity == 0) {
					v.setBackgroundResource(R.drawable.item_bg_green);
				} else if (itemWithBin.Quantity < 0) {
					v.setBackgroundResource(R.drawable.item_bg_red);
				} else if (itemWithBin.Quantity > 0) {
					v.setBackgroundResource(R.drawable.item_bg_blue);
				}
				checklist.addView(v);
				LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) v
						.getLayoutParams();
				lp.topMargin = 4;
				lp.height = 60;
			}
			if(hasone){
				defferenceitems.addView(check);
				LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) check
						.getLayoutParams();
				lp.topMargin = 10;
			}
		}
	}

	private static class WSHandler extends Handler {
		WeakReference<CheckedActivity> wactivity;

		WSHandler(CheckedActivity activity) {
			wactivity = new WeakReference<CheckedActivity>(activity);
		}

		public void handleMessage(Message msg) {
			CheckedActivity activity = wactivity.get();
			switch (msg.what) {
			case WebServicesUtil.ACTION_GetDifference: {
				SoapObject a = (SoapObject) msg.obj;
				activity.items.clear();
				int amount = a.getPropertyCount();
				for (int i = 0; i < amount; i++) {
					SoapObject itemwithbin = (SoapObject) a.getProperty(i);
					String bin = itemwithbin.getProperty("Bin") + "";
					if (activity.items.get(bin) == null) {
						List<ItemWithBin> list = new ArrayList<ItemWithBin>();
						list.add(new ItemWithBin(bin, itemwithbin
								.getProperty("ProductNumber") + "", Integer
								.valueOf(itemwithbin.getProperty("Quantity")
										+ "")));
						activity.items.put(bin, list);
					} else {
						List<ItemWithBin> list = activity.items.get(bin);
						list.add(new ItemWithBin(bin, itemwithbin
								.getProperty("ProductNumber") + "", Integer
								.valueOf(itemwithbin.getProperty("Quantity")
										+ "")));
					}
				}
				activity.refresh();
			}
				break;
			case WebServicesUtil.TIMEOUT: {
				new AlertDialog.Builder(activity).setPositiveButton("确定", null)
						.setTitle("提示").setMessage("连接超时").show();
				break;
			}
			case WebServicesUtil.NETUNREACHABLE:{
				Toast.makeText(activity, "网络无法连接或连接已取消,请稍后再试", Toast.LENGTH_SHORT).show();
				break;
			}
			default:
				break;
			}
			activity.progressDialog.dismiss();
		}
	};
	@Override
	public void onBackPressed() {
		if(progressDialog!=null&&progressDialog.isShowing()){
			progressDialog.dismiss();
		}else{
			finish();
		}
		super.onBackPressed();
	}
}
